<template>
  <view class="detail">
    <!-- 文章详情 -->
    <view class="container">
      <view v-if="loadingState" style="text-align: center;">加载中...</view>
      <view v-else>
        <view class="title">{{collectiones.title}}</view>
        <view class="userinfo">
          <view class="avatar">
            <image
              :src="collectiones.user_id[0].avatar_file?collectiones.user_id[0].avatar_file.url:'../../static/image/user.jpg'"
              mode="aspectFill"></image>
          </view>
          <view class="text">
            <view class="name">
              {{collectiones.user_id[0].nickname?collectiones.user_id[0].nickname:collectiones.user_id[0].username}}
            </view>
            <view class="small">
              <uni-dateformat :date="collectiones.publish_date" format="yyyy年MM月dd hh:mm:ss">
              </uni-dateformat> · 发布于{{collectiones.province}}
            </view>
          </view>
        </view>
        <!-- 富文本内容 -->
        <view class="content">
          <u-parse :html="collectiones?.content" :selectable="true" :tag-style="tagStyle"></u-parse>
        </view>
        <!-- 点赞 -->
        <view class="like">
          <view class="btn" @click="clickLike" :class="collectiones.isLike?'active':''">
            <text class=" iconfont icon-good-fill"></text>
            <text>{{collectiones.like_count?collectiones.like_count:'点赞'}}</text>
          </view>
          <!-- 已点赞用户头像 -->
          <view class="users">
            <template v-for="(item,index) in like_avater_arr" :key="index">
              <image :src="item.user_id[0]?.avatar_file?.url || '../../static/image/user-default.jpg'"
                mode="aspectFill"></image>
            </template>
          </view>
          <!-- 看过人数 -->
          <view class="text"><text class="num">{{collectiones.view_count}}</text>人看过</view>
        </view>
      </view>
    </view>
    <!-- 警告框 -->
    <u-toast ref="uToast" />
    <!-- 评论回复 -->
    <view class="comment" v-if="!loadingState">
      <!-- 评论为空时展示 -->
      <view v-if="!comment_data.length">
        <u-empty icon-size="200" text="抢沙发" src="https://cdn.uviewui.com/uview/empty/comment.png"></u-empty>
      </view>
      <!--  评论不为空时展示 -->
      <view class="content" v-else>
        <view class="item" v-for="item in comment_data">
          <!-- 单个评论组件 -->
          <comment-item :item="item" @del_comment="del_comment"></comment-item>
        </view>
      </view>
    </view>
    <!-- 评论框 -->
    <!-- 0表示从发布评论那触发 -->
    <comment-frame :commentObj="commentObj" @up_comment_data="getComment(0)"></comment-frame>
  </view>

</template>

<script>
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    reactive,
    ref,
    toRefs,
    watch
  } from "vue"
  import {
    store
  } from "@/uni_modules/uni-id-pages/common/store.js"
  import {
    on_like,
    artLike
  } from '../../utils/tools.js'
  import {
    useStore
  } from 'vuex'
  const db = uniCloud.database()
  const utilsObj = uniCloud.importObject("utilsObj", {
    customUI: true
  })
  export default {
    setup() {
      const vuex_store = useStore()
      const art_id = ref("")
      const loadingState = ref(true)
      const uToast = ref(null)
      const like_avater_arr = ref([])
      const comment_data = ref([])
      const data = reactive({
        // 富文本样式
        tagStyle: {
          p: "line-height:1.7em;font-size:15px;text-indent:30px;",
          img: "margin:10rpx 0;display:block;margin:auto;"
        },
        collectiones: {},
        // 发布评论时需要的数据
        commentObj: {
          comment_type: 0,
          article_id: "",
          comment_state: true
        }
      })
      watch(() => vuex_store.getters.watch_two_level_comment, (val, old) => {
        comment_data.value.forEach(item => {
          if (val._id == item._id) {
            if (val._state) {
              item.replyTotal += 1
            } else {
              item.replyTotal -= 1
            }
          }
        })
      }, {
        deep: true,
        immediate: true
      })
      // 前端无感删除评论
      const del_comment = (id) => {
        comment_data.value = comment_data.value.filter(elm => elm._id != id)
      }
      // 获取评论数据
      const getComment = async (index) => {
        // 发布评论后 300毫秒的loading状态
        if (index == 0) {
          uni.showLoading();
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast()
          }, 300);
        }
        // 两表联查获取评论数据
        let commentTemp = db.collection("pyq_comment").where(
          `article_id == "${art_id.value}" &&  comment_state == true && comment_type == 0`).orderBy(
          "comment_date desc").getTemp()
        let userTemp = db.collection("uni-id-users").field("_id,username,nickname,avatar_file").getTemp()
        const res = await db.collection(commentTemp, userTemp).get()
        comment_data.value = res.result.data
        let idArr = comment_data.value.map(item => {
          return item._id
        })
        let replyArr = await db.collection("pyq_comment").where({
          reply_comment_id: db.command.in(idArr),
          comment_state: db.command.eq(true)
        }).groupBy('reply_comment_id').groupField('count(*) as replyTatol').get()
        comment_data.value.forEach(item => {
          let index = replyArr.result.data.findIndex(find => {
            return find.reply_comment_id == item._id
          })
          if (index > -1) item.replyTotal = replyArr.result.data[index].replyTatol || 0
        })

      }
      // 文章点赞点击事件
      const clickLike = () => {
        let res = on_like(uToast)
        if (res) {
          // 前端处理点赞操作
          data.collectiones.isLike ? data.collectiones.like_count-- : data.collectiones.like_count++
          data.collectiones.isLike = !data.collectiones.isLike

          // vuex记录状态，以便主页数据能够联动
          vuex_store.commit('reset_cellback_detail_like')
          artLike(art_id.value)
          vuex_store.commit('up_cellback_detail_like', data.collectiones)
        }
      }
      // 获取点赞头像
      const like_avater = () => {
        // 两表联查
        let likeTemp = db.collection("pyq_like").where(`article_id == "${art_id.value}"`).getTemp()
        let userTemp = db.collection("uni-id-users").field("_id,avatar_file").getTemp()
        db.collection(likeTemp, userTemp).orderBy("publish_date desc").limit(3).get().then(res => {
          like_avater_arr.value = res.result.data.reverse()
        })
      }
      // 获取文章详情数据
      const getDate = () => {
        // 三表联查
        const artTemp = db.collection("pyq_article").where(`_id == "${art_id.value}"`).getTemp()
        const userTemp = db.collection("uni-id-users").field("_id,username,avatar_file,nickname").getTemp()
        const likeTemp = db.collection("pyq_like")
          .where(`article_id == "${art_id.value}" && user_id ==$cloudEnv_uid`)
          .getTemp()
        let tempArr = [artTemp, userTemp]
        // 是否点赞需要用户登录后 用用户id来查询，为了保证未登录状态也能正常浏览文章，所以通过这种数组的添加的方式来处理
        if (store.hasLogin) {
          tempArr.push(likeTemp)
        }
        db.collection(...tempArr).get({
          getOne: true
        }).then(res => {
          console.log(res)
          data.collectiones = res.result.data
          let isLike = false
          // 通过点赞的长度来确认用户是否对改文章点赞
          if (store.hasLogin) {
            isLike = res.result.data._id.pyq_like.length ? true : false
          }
          res.result.data.isLike = isLike
          loadingState.value = false
        })
      }
      onLoad((e) => {
        // 判断是否传送了id，没有就回到index页面
        if (!e.id) {
          setTimeout(() => {
            uni.reLaunch({
              url: "/pages/index/index"
            })
          }, 300)
        }
        // 获取传递过来的文章id
        art_id.value = e.id
        // 这个在评论时需要
        data.commentObj.article_id = e.id
        // 阅读量加一
        utilsObj.operation("pyq_article", "view_count", e.id, 1).then(res => {})
        getDate()
        like_avater()
        getComment()
      })
      return {
        ...toRefs(data),
        art_id,
        clickLike,
        loadingState,
        uToast,
        like_avater_arr,
        comment_data,
        getComment,
        del_comment
      }
    }
  }
</script>

<style lang="scss" scoped>
  .detail {
    background: #f8f8f8;
    // 兼容h5 与 微信小程序的全屏高度
    min-height: calc(100vh - var(--window-top));

    .container {
      padding: 30rpx;
      background: #fff;

      .title {
        font-size: 46rpx;
        color: #333;
        line-height: 1.4em;
        font-weight: 600;
        width: 650rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }

      .userinfo {
        padding: 20rpx 0 50rpx;
        display: flex;
        align-items: center;

        .avatar {
          width: 60rpx;
          height: 60rpx;
          padding-right: 15rpx;

          image {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }
        }

        .text {
          font-size: 28rpx;
          color: #555;

          .small {
            font-size: 20rpx;
            color: #999;
          }
        }
      }

      .like {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 80rpx 50rpx 50rpx;

        .btn {
          width: 260rpx;
          height: 120rpx;
          background: #e4e4e4;
          border-radius: 100rpx;
          color: #fff;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          font-size: 28rpx;

          .iconfont {
            font-size: 50rpx;
          }

          &.active {
            background: #0199FE;
          }
        }

        .text {
          font-size: 26rpx;
          color: #666;

          .num {
            color: #0199FE
          }

          .spot {
            padding: 0 10rpx;
          }
        }

        .users {
          display: flex;
          justify-content: center;
          padding: 30rpx 0;

          image {
            width: 50rpx;
            height: 50rpx;
            border-radius: 50%;
            border: 3px solid #fff;
            margin-left: -20rpx;
          }
        }
      }
    }

    .content {
      .item {
        border-bottom: 1px solid #e3dcdc;
        margin: 0px 20rpx;
        padding-top: 26rpx;
      }
    }
  }
</style>